package com.zj.apigateway.filter;

import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import com.zj.apigateway.client.UserClient;
import com.zj.apigateway.common.User;
import com.zj.apigateway.utils.JwtTokenUtil;
import org.apache.commons.lang.StringUtils;
import org.apache.http.HttpStatus;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;

import static org.springframework.cloud.netflix.zuul.filters.support.FilterConstants.PRE_DECORATION_FILTER_ORDER;
import static org.springframework.cloud.netflix.zuul.filters.support.FilterConstants.PRE_TYPE;

/**
 * @Auther: zj
 * @Date: 2018/11/22 14:53
 * @Description:
 */
@Component
public class TokenFilter extends ZuulFilter {
    @Autowired
    UserClient userClient;
    @Autowired
    JwtTokenUtil jwtTokenUtil;

    @Override
    public String filterType() {
        return PRE_TYPE;
    }

    @Override
    public int filterOrder() {
        return PRE_DECORATION_FILTER_ORDER -1;
    }

    @Override
    public boolean shouldFilter() {
        RequestContext requestContext = RequestContext.getCurrentContext();
        HttpServletRequest request = requestContext.getRequest();

        if ("/user/login/customer".equals( request.getRequestURI())) {
            return false;
        }
        if ("/user/login/admin".equals( request.getRequestURI())) {
            return false;
        }
        if ("/user/auth/register".equals( request.getRequestURI())) {
            return false;
        }
        if ("/user/getVerifyCode".equals( request.getRequestURI())) {
            return false;
        }

        return true;
    }

    @Override
    public Object run() throws ZuulException {
        RequestContext requestContext = RequestContext.getCurrentContext();
        HttpServletRequest request = requestContext.getRequest();

        String tokenHeader="Authorization";
        String tokenHead="Bearer ";
        String authHeader = request.getHeader(tokenHeader);
        if (authHeader == null && !authHeader.startsWith(tokenHead)) {
            requestContext.setSendZuulResponse( false );
            requestContext.setResponseStatusCode( HttpStatus.SC_UNAUTHORIZED );
            requestContext.setResponseBody( "{\"result\":\"token不存在或格式不对\"}" );
            requestContext.getResponse().setContentType( "text/html;charset=UTF-8" );
        }

        String authToken = authHeader.substring( tokenHead.length() ); // token is the part after "Bearer "
        String username = jwtTokenUtil.getUsernameFromToken( authToken );

        if (username == null) {
            requestContext.setSendZuulResponse( false );
            requestContext.setResponseStatusCode( HttpStatus.SC_UNAUTHORIZED );
            requestContext.setResponseBody( "{\"result\":\"用户名不存在\"}" );
            requestContext.getResponse().setContentType( "text/html;charset=UTF-8" );
        }

        User user = userClient.getUserByUsername( username );//调user服务，去查数据库
        System.out.println( user );

        if (user==null){
            requestContext.setSendZuulResponse( false );
            requestContext.setResponseStatusCode( HttpStatus.SC_UNAUTHORIZED );
            requestContext.setResponseBody( "{\"result\":\"网络超时，发生熔断，请重试\"}" );
            requestContext.getResponse().setContentType( "text/html;charset=UTF-8" );
        }

        //校验token
        if (!jwtTokenUtil.validateToken( authToken, user )) {
            requestContext.setSendZuulResponse( false );
            requestContext.setResponseStatusCode( HttpStatus.SC_UNAUTHORIZED );
            requestContext.setResponseBody( "{\"result\":\"token校验不通过\"}" );
            requestContext.getResponse().setContentType( "text/html;charset=UTF-8" );
        }

        return null;
    }
}
